package com.wzy.server.task;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.wzy.server.pojo.Employee;
import com.wzy.server.pojo.MailConstants;
import com.wzy.server.pojo.MailLog;
import com.wzy.server.service.IEmployeeService;
import com.wzy.server.service.IMailLogService;
import com.wzy.server.service.impl.EmployeeServiceImpl;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @Desc  邮件发送定时任务
 */
@Component
public class MailTask {
    @Autowired
    private IMailLogService mailLogService;
    @Autowired
    private IEmployeeService employeeService;
    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Scheduled(cron = "0/10 * * * * ?")//十秒执行一次
    public void mailTask(){
        List<MailLog> list = mailLogService.list(new QueryWrapper<MailLog>()//按条件查询数据库里的所有消息
                .eq("status",0)//状态为 消息投递中
                .lt("tryTime", LocalDateTime.now()));//重试时间小于当前时间
        //遍历要去发的信息，并且重试的时间到了
        list.forEach(mailLog -> {
            String msgId = mailLog.getMsgId();
            //重试次数超过最大次数3，投递失败
            if (mailLog.getCount()>= 3) {
                mailLogService.update(new UpdateWrapper<MailLog>()
                        .eq("msgId",mailLog.getMsgId())
                        .set("status",2)
                        .set("updateTime",LocalDateTime.now()));
            }
            mailLogService.update(new UpdateWrapper<MailLog>()//重发状态变更
                    .eq("msgId",mailLog.getMsgId())//不加为全局更新
                    .set("count",mailLog.getCount()+1)//重试次数加1
                    .set("updateTime",LocalDateTime.now())//更新时间
                    .set("tryTime",LocalDateTime.now().plusMinutes(MailConstants.MSG_TIMEOUT)));//重试时间
//            获取员工信息
            Employee emp = employeeService.getEmployee(mailLog.getEid()).get(0);
            //发送信息
            rabbitTemplate.convertAndSend(MailConstants.MAIL_EXCHANGE_NAME,MailConstants.MAIL_ROUTING_KEY_NAME
                    ,emp,new CorrelationData(mailLog.getMsgId()));
        });
    }
}
